//
//  YCCameraViewController.m
//  YCCamera
//
//  Created by YC on 2017/7/18.
//  Copyright © 2017年 YC. All rights reserved.
//

#import "YCCameraViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <AssetsLibrary/AssetsLibrary.h>

@interface YCCameraViewController ()<UIAlertViewDelegate> {
    
}

/**
 *  捕获设备，通常是前置摄像头，后置摄像头，麦克风（音频输入）
 */
@property (nonatomic, strong) AVCaptureDevice           *device;
/**
 *  设备之间的数据传递  第一个创建
 */
@property (nonatomic, strong)AVCaptureSession           * session;
/**
 *  输入流
 */
@property (nonatomic, strong)AVCaptureDeviceInput       * videoInput;
/**
 *  照相机
 */
@property (nonatomic, strong)AVCaptureStillImageOutput  * stillImageOutput;
/**
 *  显示层 (相框) 要第二个创建
 */
@property (nonatomic, strong)AVCaptureVideoPreviewLayer * previewLayer;

@end

@implementation YCCameraViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil
                         bundle:(NSBundle *)nibBundleOrNil {
    
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    
    if (self) {
        [self initSession];
    }
    
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setUpCameraLayer];
    [self setUpFocusView];
    [self setUpFlashButton];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:YES];
    
    [self getAVAuthorization];
    
    if (self.session) {
        [self.session startRunning];
    }
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear: animated];
    
    if (self.session) {
        [self.session stopRunning];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
    NSLog(@"相机内存警告");
}

- (void)dealloc {
    NSLog(@"%s",__func__);
}

/**
 *  获取相机权限
 */
- (void)getAVAuthorization {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus ==AVAuthorizationStatusRestricted || authStatus ==AVAuthorizationStatusDenied) {
        [self alertWithTitle:@"无法使用相机" message:@"请在iPhone的\"设置-隐私-相机中允许访问相机\""];
    }
}

/**
 *  获取相册权限
 */
- (void)getALAuthorization {
    ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];
    if (author ==ALAuthorizationStatusRestricted || author ==ALAuthorizationStatusDenied){
        [self alertWithTitle:@"无法使用相册" message:@"请在iPhone的\"设置-隐私-照片中允许访问相机\""];
    }
}

/**
 *  初始化Session
 */
- (void)initSession {
    self.session = [[AVCaptureSession alloc] init];
    self.session.sessionPreset = AVCaptureSessionPresetPhoto;
    
    self.device = [self backCamera];
    
    self.videoInput = [[AVCaptureDeviceInput alloc] initWithDevice:self.device error:nil];
    
    self.stillImageOutput = [[AVCaptureStillImageOutput alloc] init];
    NSDictionary * outputSettings = [[NSDictionary alloc] initWithObjectsAndKeys:AVVideoCodecJPEG,AVVideoCodecKey, nil];
    //以JPEG的图片格式输出图片
    [self.stillImageOutput setOutputSettings:outputSettings];
    
    if ([self.session canAddInput:self.videoInput]) {
        [self.session addInput:self.videoInput];
    }
    
    if ([self.session canAddOutput:self.stillImageOutput]) {
        [self.session addOutput:self.stillImageOutput];
    }
    
    if ([self.device lockForConfiguration:nil]) {
        //自动闪光灯，
        if ([self.device isFlashModeSupported:AVCaptureFlashModeAuto]) {
            [self.device setFlashMode:AVCaptureFlashModeAuto];
        }
        //            //自动白平衡,但是好像一直都进不去
        //            if ([_device isWhiteBalanceModeSupported:AVCaptureWhiteBalanceModeAutoWhiteBalance]) {
        //                [_device setWhiteBalanceMode:AVCaptureWhiteBalanceModeAutoWhiteBalance];
        //            }
        
        [self.device unlockForConfiguration];
    }
}

/**
 *  设置相机layer
 */
- (void)setUpCameraLayer{
    
    if (self.previewLayer == nil) {
        self.previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];
        
        UIView * view = self.cameraView;
        CALayer * viewLayer = [view layer];
        [viewLayer setMasksToBounds:YES];
        
        CGRect bounds = [view bounds];
        
        [self.previewLayer setFrame:bounds];
        [self.previewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
        
        [viewLayer insertSublayer:self.previewLayer below:[[viewLayer sublayers] objectAtIndex:0]];
    }
}

/**
 *  设置聚焦View
 */
- (void)setUpFocusView{
    self.focusView.layer.borderWidth = 1.0;
    self.focusView.layer.borderColor =[UIColor yellowColor].CGColor;
    self.focusView.hidden = true;
}

/**
 *  设置闪光灯Button
 */
- (void)setUpFlashButton {
    self.flashButton.layer.cornerRadius=10;
    self.flashButton.layer.borderColor=[UIColor whiteColor].CGColor;
    self.flashButton.layer.borderWidth=1;
}

/**
 *  获取前后摄像头对象的方法
 */
- (AVCaptureDevice *)cameraWithPosition:(AVCaptureDevicePosition) position {
    NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    for (AVCaptureDevice *device in devices) {
        if ([device position] == position) {
            return device;
        }
    }
    return nil;
}

/**
 *  前置摄像头
 */
- (AVCaptureDevice *)frontCamera {
    return [self cameraWithPosition:AVCaptureDevicePositionFront];
}

/**
 *  后置摄像头
 */
- (AVCaptureDevice *)backCamera {
    return [self cameraWithPosition:AVCaptureDevicePositionBack];
}

/**
 *  设置闪光灯模式
 */
- (IBAction)clickFlashButton:(UIButton *)sender {
    
    if ([self.device hasFlash] && [self.device hasTorch]) {
        
        [self.device lockForConfiguration:nil];
        
        switch (sender.tag) {
            case 0:{
                [self.device setFlashMode:AVCaptureFlashModeOn];
                sender.tag = 1;
                [sender setTitle:@"⚡️打开" forState:UIControlStateNormal];
            }
                break;
            case 1:{
                [self.device setFlashMode:AVCaptureFlashModeOff];
                sender.tag = 2;
                [sender setTitle:@"⚡️关闭" forState:UIControlStateNormal];
            }
                break;
            case 2:{
                [self.device setFlashMode:AVCaptureFlashModeAuto];
                sender.tag = 0;
                [sender setTitle:@"⚡️自动" forState:UIControlStateNormal];
            }
                break;
                
            default:
                break;
        }
        
        [self.device unlockForConfiguration];
    }
}

/**
 *  点击取消按钮
 */
- (IBAction)clickCancelButton:(UIButton *)sender {
    [self dismissViewControllerAnimated:true completion:nil];
}

/**
 *  点击拍照按钮
 */
- (IBAction)clickCameraButton:(UIButton *)sender {
    AVCaptureConnection * videoConnection = [self.stillImageOutput connectionWithMediaType:AVMediaTypeVideo];
    if (!videoConnection) {
        NSLog(@"拍照失败");
        return;
    }
    
    [self.stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
        if (imageDataSampleBuffer == NULL) {
            return;
        }
        
        //照片
        NSData * imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
        
        self.preview.hidden = false;
        self.previewImageView.image = [UIImage imageWithData:imageData];
        
        self.previewImageView.image = [self waterMarkImage:[UIImage imageWithData:imageData] withText:@" iOS 责任人 2017-02-28 22:22:22"];
        
        [self.session stopRunning];
    }];
}

/**
 *  点击切换摄像头
 */
- (IBAction)clickChangeButton:(UIButton *)sender {
    NSUInteger cameraCount = [[AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo] count];
    if (cameraCount > 1) {
        NSError *error;
        
        //给摄像头的切换添加翻转动画
        CATransition *animation = [CATransition animation];
        animation.duration = 0.5f;
        animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
        animation.type = @"oglFlip";
        
        AVCaptureDevice *newCamera = nil;
        AVCaptureDeviceInput *newVideoInput = nil;
        //拿到另外一个摄像头位置
        AVCaptureDevicePosition position = [[_videoInput device] position];
        
        if (position == AVCaptureDevicePositionBack) {
            newCamera = [self cameraWithPosition:AVCaptureDevicePositionFront];
            animation.subtype = kCATransitionFromRight;
        }else if (position == AVCaptureDevicePositionFront) {
            newCamera = [self cameraWithPosition:AVCaptureDevicePositionBack];
            animation.subtype = kCATransitionFromLeft;
        }
        
        newVideoInput = [[AVCaptureDeviceInput alloc] initWithDevice:newCamera error:&error];
        
        [self.previewLayer addAnimation:animation forKey:nil];
        
        if (newVideoInput != nil) {
            [self.session beginConfiguration];
            [self.session removeInput:self.videoInput];
            if ([self.session canAddInput:newVideoInput]) {
                [self.session addInput:newVideoInput];
                [self setVideoInput:newVideoInput];
            } else {
                [self.session addInput:self.videoInput];
            }
            [self.session commitConfiguration];
        } else if (error) {
            NSLog(@"打开失败 %@", error);
        }
    }
}

- (IBAction)tapCameraView:(UITapGestureRecognizer *)sender {
    CGPoint point = [sender locationInView:sender.view];
    [self focusAtPoint:point];
}

//AVCaptureFlashMode  闪光灯
//AVCaptureFocusMode  对焦
//AVCaptureExposureMode  曝光
//AVCaptureWhiteBalanceMode  白平衡
//闪光灯和白平衡可以在生成相机时候设置
//曝光要根据对焦点的光线状况而决定,所以和对焦一块写
//point为点击的位置
- (void)focusAtPoint:(CGPoint)point{
    
    CGSize size = self.view.bounds.size;
    CGPoint focusPoint = CGPointMake( point.y /size.height ,1-point.x/size.width );
    NSError *error;
    if ([self.device lockForConfiguration:&error]) {
        
        //对焦模式和对焦点
        if ([self.device isFocusModeSupported:AVCaptureFocusModeAutoFocus]) {
            [self.device setFocusPointOfInterest:focusPoint];
            [self.device setFocusMode:AVCaptureFocusModeAutoFocus];
        }
        //曝光模式和曝光点
        if ([self.device isExposureModeSupported:AVCaptureExposureModeAutoExpose ]) {
            [self.device setExposurePointOfInterest:focusPoint];
            [self.device setExposureMode:AVCaptureExposureModeAutoExpose];
        }
        
        [self.device unlockForConfiguration];
        //设置对焦动画
        self.focusView.center = point;
        self.focusView.hidden = NO;
        
        [UIView animateWithDuration:0.3 animations:^{
            _focusView.transform = CGAffineTransformMakeScale(1.25, 1.25);
        }completion:^(BOOL finished) {
            [UIView animateWithDuration:0.5 animations:^{
                _focusView.transform = CGAffineTransformIdentity;
            } completion:^(BOOL finished) {
                _focusView.hidden = YES;
            }];
        }];
    }
    
}

/**
 *  调整焦距
 */
//-(void)adjustFocalDistance:(UIButton *)sender{
    
//    kCameraScale += 1.0;
//    
//    if(kCameraScale > 4.0) {
//        kCameraScale=1.0;
//    }
    
//    [CATransaction begin];
//    [CATransaction setAnimationDuration:0.2];
//    
//    [_previewLayer setAffineTransform:CGAffineTransformMakeScale(kCameraScale, kCameraScale)];
//    //改变焦距
//    AVCaptureConnection *connect=[self.stillImageOutput connectionWithMediaType:AVMediaTypeVideo];
//    connect.videoScaleAndCropFactor = kCameraScale;
//    
//    [CATransaction commit];
    
//}

/**
 *  重新拍摄
 */
- (IBAction)clickAgainButton:(UIButton *)sender {
    
    self.preview.hidden = true;
    self.previewImageView.image = nil;
    
    [self.session startRunning];
    
}

/**
 *  保存到相册
 */
- (IBAction)clickSaveImageButton:(id)sender {
    [self saveImageToPhotoAlbum:self.previewImageView.image];
}

/**
 *  使用照片
 */
- (IBAction)clickUseButton:(UIButton *)sender {
    
    if (self.imageBlock) {
        self.imageBlock(self.previewImageView.image);
    }
    
    [self dismissViewControllerAnimated:true completion:nil];
}

/**
 *  给图片添加文字水印
 */
- (UIImage *)waterMarkImage:(UIImage *)image withText:(NSString *)text {
    
    CGFloat width = image.size.width;
    CGFloat height = image.size.height;
    
    CGFloat watermarkHeight = height / 20;
    
    UIGraphicsBeginImageContext(image.size);
    //    在画布大小
    
    [image drawInRect:CGRectMake(0, 0, width, height)];
    
    CGRect rect = CGRectMake(8, height - watermarkHeight, width, watermarkHeight);
    
    NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:height / 24],
                          NSForegroundColorAttributeName : [UIColor redColor],
                          NSBackgroundColorAttributeName: [UIColor colorWithRed:204/255.0 green:204/255.0 blue:204/255.0 alpha:0.5]};
    
    [text drawInRect:rect withAttributes:dic];
    
    UIImage *returnImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return returnImage;
}

//保存照片至本机
- (void)saveImageToPhotoAlbum:(UIImage*)image {
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    if (error != NULL) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"出错了!"
                                                        message:@"存不了T_T"
                                                       delegate:nil
                                              cancelButtonTitle:@"关闭"
                                              otherButtonTitles:nil, nil];
        [alert show];
    } else {
        NSLog(@"保存成功!");
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}


#pragma mark - UIAlertView Delegate

- (void)alertWithTitle:(NSString *)title message:(NSString *)message {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
                                                    message:message
                                                   delegate:self
                                          cancelButtonTitle:@"确定"
                                          otherButtonTitles:@"设置", nil];
    
    [alert show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    switch (buttonIndex) {
        case 0:{
            [self dismissViewControllerAnimated:true completion:nil];
        }
            break;
        case 1:{
            //跳转到设置界面
            NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            if ([[UIApplication sharedApplication]canOpenURL:url]) {
                [[UIApplication sharedApplication]openURL:url];
            }
        }
            break;
            
        default:
            break;
    }

}

@end
